package com.disruptor.sample._01base.run;

import com.disruptor.sample.common.dto.LongEvent;
import com.lmax.disruptor.RingBuffer;
import com.lmax.disruptor.dsl.Disruptor;
import com.lmax.disruptor.util.DaemonThreadFactory;
import java.nio.ByteBuffer;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class LongEventMain {

  public static void main(String[] args) throws Exception {
    // 1 指定环形缓冲区的大小，必须是2的幂。
    int bufferSize = 1024;

    // 2 创建 Disruptor
    Disruptor<LongEvent> disruptor =
        new Disruptor<>(LongEvent::new, bufferSize, DaemonThreadFactory.INSTANCE);

    // 3 连接处理程序，匿名函数绑定了一个消费者
    disruptor.handleEventsWith((event, sequence, endOfBatch) -> log.info("Event: " + event));

    // 4 启动 Disruptor，启动所有线程运行
    disruptor.start();

    // 5 从 Disruptor 获取环形缓冲区以用于发布
    RingBuffer<LongEvent> ringBuffer = disruptor.getRingBuffer();
    ByteBuffer byteBuffer = ByteBuffer.allocate(8);
    for (long value = 0; true; value++) {
      byteBuffer.putLong(0, value);
      ringBuffer.publishEvent((event, sequence, buffer) -> event.setValue(buffer.getLong(0)), byteBuffer);
      Thread.sleep(1000);
    }
  }
}
